using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using WenRuo;

public class ScrollViewLayout : RecycleView
{
    public CellData[] cellDatas;
    public List<CelliItemView> celliItemViews; 
    public List<int> inCellView = new List<int>();

    void Start()
    {
    }

    public virtual void ShowList(CellData[] _CellDatas)
    {
        int showCount = _CellDatas.Length;
        SetContentRect(showCount, dataCount);

        if (celliItemViews != null || celliItemViews.Count > 0)
        {
            int count = celliItemViews.Count;
            for (int i = 0; i < count; i++)
            {
                SetPoolsObj(celliItemViews[i].gameObject);
            }
        }


        CellData cellData = null;
        CelliItemView cellView = null;
        for (int i = 0; i < showCount; i++)
        {
            cellData = _CellDatas[i];
            cellData.LocalPos = GetCellPos(i);
            cellData.Index = i;

            if (IsOutRange(cellData.LocalPos))
            {
                continue;
            }
 
            SetGameObject(  cellData);
        }

        this.cellDatas = _CellDatas;
        dataCount = showCount;
        OnDragListener(Vector2.zero);
        UpdateCheck();
    }
 
    protected override void UpdateCheck()
    {
        SetminMaxIndex(); 
        inCellView.Clear();
        for (int i = minIndex; i <= maxIndex; i++)
        {
            inCellView.Add(i);
        }

        CelliItemView cellView;
        int count = celliItemViews.Count;
        for (int i = 0; i < count; i++)
        {
            cellView = celliItemViews[i];
            if (IsOutRange(cellView._CellData.LocalPos))
            {
                SetPoolsObj(cellView.gameObject);
                celliItemViews.RemoveAt(i);
                i--;
                count--;
            }
            else
            {
                inCellView.Remove(cellView._CellData.Index);
            }
        }

        int index = 0;
        count = inCellView.Count;
        for (int i = 0; i < count; i++)
        {
            index = inCellView[i];
            if (index >= dataCount)
            {
                continue;
            }

           
            
            cellDatas[index].Index = index;
            SetGameObject(cellDatas[index]);
        }
    }

    protected void SetGameObject(  CellData cellData)
    {
        GameObject obj = GetPoolsObj();
        CelliItemView   cellView = obj.GetComponent<CelliItemView>();
        if (cellView == null)
            cellView = obj.AddComponent<CelliItemView>();
        
        cellView.SetData(cellData);
            
        celliItemViews.Add(cellView);

        SetGameObject(obj, cellData.LocalPos, cellData.Index.ToString());
    }
}